package com.ibeetl.cms.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.ibeetl.admin.console.web.dto.SiteExcelImportData;
import com.ibeetl.admin.core.service.CorePlatformService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.util.*;
import com.ibeetl.cms.entity.*;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.web.query.*;

/**
 * 博士后站点配置 接口
 */
@Controller
public class SiteController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/site";


    @Autowired
    private SiteService siteService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("cms.site.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/site/index.html");
        view.addObject("search", SiteQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.site.query")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/site/edit.html");
        CoreUser currentUser = platformService.getCurrentUser();
        Site site = siteService.queryById(id);
        view.addObject("name", currentUser.getName());
        view.addObject("site", site);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.site.query")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/site/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult<PageQuery> list(SiteQuery condtion) {
        PageQuery page = condtion.getPageQuery();
        siteService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class) Site site) {
        site.setState("S1");
        siteService.save(site);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) Site site) {
        boolean success = siteService.updateTemplate(site);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


    @GetMapping(MODEL + "/view.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult<Site> queryInfo(Integer id) {
        Site site = siteService.queryById(id);
        return JsonResult.success(site);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        siteService.batchDelSite(idList);
        return new JsonResult().success();
    }

    /**
     * 失效
     *
     * @param ids
     * @return
     */
    @PostMapping(MODEL + "/invalid.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult invalid(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        siteService.invalid(idList);
        return JsonResult.success();
    }


    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, SiteQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此siteService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate = "excelTemplates/admin/user/site_collection_template.xls";
        PageQuery<Site> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<Site> list = siteService.queryByCondition(page).getList();
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if (is == null) {
                throw new PlatformException("模板资源不存在：" + excelTemplate);
            }
            FileItem item = fileService.createFileTemp("博士后站点配置_" + DateUtil.now("yyyyMMddHHmmss") + ".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }

    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.site.query")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();

        InputStream inputXML = Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplates/admin/user/site_mapping.xml");
        XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
        InputStream inputXLS = ins;
        List<SiteExcelImportData> dicts = new ArrayList<SiteExcelImportData>();
        Map beans = new HashMap();
        beans.put("list", dicts);
        ReaderConfig.getInstance().setSkipErrors(true);
        XLSReadStatus readStatus = mainReader.read(inputXLS, beans);
        for (SiteExcelImportData site : dicts) {//默认导入状态为S1（正常）
            site.setState("S1");
        }
        List<XLSReadMessage> errors = readStatus.getReadMessages();
        try {
            this.siteService.batchInsert(dicts);
            return JsonResult.success();
        } catch (Exception ex) {
            return JsonResult.failMessage(ex.getMessage());
        }
    }

}
